﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.App.DTO;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Company
{
    public class CompanyQueryCommandHandler : IRequestHandler<CompanyQueryCommand, APIResult<CompanyDto>>
    {
        private readonly IBaseRepository<T_Company> companyRepository;
        private readonly IBaseRepository<T_CompanyAddress> addressRepository;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="companyRepository"><公司仓储/param>
        /// <param name="addressRepository">地址仓储</param>
        /// <param name="mapper">映射</param>
        public CompanyQueryCommandHandler(IBaseRepository<T_Company> companyRepository, IBaseRepository<T_CompanyAddress> addressRepository, IMapper mapper)
        {
            this.companyRepository = companyRepository;
            this.addressRepository = addressRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<CompanyDto>> Handle(CompanyQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<CompanyDto> result = new APIResult<CompanyDto>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            
            var dto = companyRepository.GetAll().AsNoTracking().FirstOrDefault(x => x.Batch == request.Batch && x.CompanyType == request.CompanyType);
            if (dto != null) 
            {
                var model = mapper.Map<CompanyDto>(dto);
                if (!string.IsNullOrEmpty(dto.CompanyAddress))
                {
                    var arrlist = dto.CompanyAddress.Split(',').Select(x => Convert.ToInt32(x));
                    var strings = addressRepository.GetAll().Where(x => arrlist.Contains(x.ID)).Select(x => x.AddressName);
                    model.Address = string.Join(" ", strings);
                }
                result.Data = model;
            }
            

            return Task.FromResult(result);
        }
    }
}
